<?php
declare (strict_types = 1);

namespace app\controller\admin;

use think\Request;
use app\model\AdminUser;
use app\model\AdminUserLoginLog;
use think\facade\Log;
use think\facade\Session;
use think\Validate;
use app\traits\MyControllerTrait;
use app\model\AdminConfig;
use app\model\MyRedis;

class AuthController
{
    use MyControllerTrait;

    /**
     * 验证码显示链接[图片]
     *
     * @return \think\Response
     */
    public function getCaptcha()
    {
        return $this->generateCaptcha();
    }// getCaptcha() end

    public function loginPage(Request $request)
    {
        $token_key   = AdminUser::getTokenKey((int)session('admin_user.id'));
        $redis       = MyRedis::getRedisInstance();
        $redis_token = $redis->get($token_key);
        if (
            Session::has($token_key) &&
            $redis_token === Session::get($token_key)
        ) return redirect('/admin/index', 302);

        $data = [
            'title'     => '管理员-登录',
            'uri'       => "/admin/user/login",
            'name'      => AdminConfig::getContent('website'),
            '__token__' => $request->buildToken()
        ];
        return view('/admin/auth/login', $data);
    }// loginPage() end

    public function login(Request $request)
    {
        $account  = $request->post('account/s', '');
        $password = $request->post('password/s', '');
        $captcha  = $request->post('captcha/s', '');
        $response = ['code' => 0, 'message' => '失败'];

        // use validate
        $check_data = [
            'account'   => $account,
            'password'  => $password,
            'captcha'   => $captcha
        ];
        $rules = [
            'account|账户'   => 'require|alphaNum|max:15',
            'password|密码'  => 'require|alphaNum|max:20',
            'captcha|验证码' => 'require|captcha|max:10',
        ];
        $message = [
            'account.require'   => ':attribute 不能为空',
            'account.alphaNum'  => ':attribute 只支持数字和字母',
            'account.max'       => ':attribute 长度不能超过 15',
            'password.require'  => ':attribute 不能为空',
            'password.alphaNum' => ':attribute 只支持数字和字母',
            'password.max'      => ':attribute 长度不能超过 20',
        ];
        $validate = new Validate;
        $validate->message($message);
        if ($validate->check($check_data, $rules) === false) return json(['code' => 0, 'message' => $validate->getError()]);

        $user = AdminUser::whereRaw('account = :account', ['account' => $account])->findOrEmpty();
        if ($user->isEmpty()) return json(['code' => 0, 'message' => '账户或密码错误']);

        if ($user->password !== AdminUser::generatePassword($password, $user->salt))  return json($response);
        if ($request->checkToken('__token__') === false) return json(['code' => 0, 'message' => '页面失效,请刷新页面']);

        $user = AdminUser::whereRaw('account = :account', ['account' => $account])->findOrEmpty();
        // write session
        try {
            $admin_role_id = $user->admin_role_id ?? 0;
            AdminUser::generateLoginSession($user->toArray());
            AdminUserLoginLog::generateLog($user->id, $request->ip(), '管理员登录');
        } catch (\Exception $e) {
            $message = [
                'function'  => __CLASS__.'->'.__FUNCTION__.'():'.__LINE__,
                'error'     => $e->getMessage()
            ];
            Log::channel('admin-controller')->error(str_replace('\\/', '/', json_encode($message, JSON_UNESCAPED_UNICODE)));
            return json(['code' => 0, 'message' => '登录失败']);
        }
        return json(['code' => 1, 'message' => '登录成功']);
    }// login() end

    public function logout(Request $request)
    {
        AdminUserLoginLog::generateLog(Session::get('admin_user.id'), $request->ip(), '管理员登出');
        // destroy session
        Session::clear();
        $redis = MyRedis::generateRedisInstance();
        $redis->del('admin_user.token');
        return redirect('/admin/user/login', 302);
    }// logout() end
}
